﻿using Abp.Domain.Repositories;
using Microsoft.AspNetCore.Mvc;
using shenghua.Order.Orders;
using shenghua.Payment.Payments;
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace shenghua.Controllers
{
    [Route("api/[controller]/[action]")]
    public class PaymentController : shenghuaControllerBase
    {
        private readonly OrderManager _orderManager;

        public PaymentController(
            OrderManager orderManager)
        {
            _orderManager = orderManager;
        }

        /// <summary>
        /// 支付同步回调接口，由于要用到requset，写在了controller层
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public async Task PaymentReturn()
        {
            await _orderManager.PaymentReturn(GetRequestGet());
            string redirect = Request.Query["redirect"];
            Response.Redirect(redirect);
        }

        /// <summary>
        /// 支付异步回调接口，由于要用到requset，写在了controller层
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public async Task PaymentNotify()
        {
            await _orderManager.PaymentNotify(GetRequestPost());
        }


        private Dictionary<string, string> GetRequestGet()
        {
            int i = 0;
            Dictionary<string, string> sArray = new Dictionary<string, string>();
            var keys = Request.Query.Keys.ToArray();
            for (i = 0; i < keys.Length; i++)
            {
                sArray.Add(keys[i], Request.Query[keys[i]]);
            }
            return sArray;
        }

        private Dictionary<string, string> GetRequestPost()
        {
            int i = 0;
            Dictionary<string, string> sArray = new Dictionary<string, string>();
            var keys = Request.Form.Keys.ToArray();
            for (i = 0; i < keys.Length; i++)
            {
                sArray.Add(keys[i], Request.Form[keys[i]]);
            }
            return sArray;
        }
    }
}
